﻿@inject HttpClient Http
@inject NavigationManager NavigationManager
@inject IStringLocalizerFactory LocalizerFactory
@using Microsoft.Extensions.Localization

<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">@Localizer["Title"]</h3>

    @if (IsLoading)
    {
        <LoadingIndicator />
    }
    else
    {
        @if (TwoFactorEnabled)
        {
            <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">@Localizer["EnabledMessage"]</div>
            <Button Color="danger" OnClick="DisableTwoFactor">@Localizer["DisableButton"]</Button>
        }
        else
        {
            <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">@Localizer["DisabledMessage"]</div>
            <Button Color="success" OnClick="EnableTwoFactor">@Localizer["EnableButton"]</Button>
        }
    }
</div>

@code {
    private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.Security.TwoFactorAuthenticationSection", "AliasVault.Client");

    /// <summary>
    /// Gets or sets a value indicating whether Two-Factor Authentication is enabled.
    /// </summary>
    [Parameter]
    public bool TwoFactorEnabled { get; set; }

    /// <summary>
    /// Event callback that is invoked when the Two-Factor Authentication status changes.
    /// </summary>
    [Parameter]
    public EventCallback OnStatusChanged { get; set; }

    private bool IsLoading { get; set; } = true;

    /// <summary>
    /// Loads the Two-Factor Authentication status from the server.
    /// </summary>
    /// <returns>A task representing the asynchronous operation.</returns>
    public async Task LoadData()
    {
        IsLoading = true;
        StateHasChanged();

        var twoFactorResponse = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("v1/TwoFactorAuth/status");
        if (twoFactorResponse is not null)
        {
            TwoFactorEnabled = twoFactorResponse.TwoFactorEnabled;
        }

        IsLoading = false;
        StateHasChanged();
    }

    /// <summary>
    /// Navigates to the Enable Two-Factor Authentication page.
    /// </summary>
    private void EnableTwoFactor()
    {
        NavigationManager.NavigateTo("settings/security/enable-2fa");
    }

    /// <summary>
    /// Navigates to the Disable Two-Factor Authentication page.
    /// </summary>
    private void DisableTwoFactor()
    {
        NavigationManager.NavigateTo("settings/security/disable-2fa");
    }

    /// <summary>
    /// Represents the result of the Two-Factor Authentication status check.
    /// </summary>
    private sealed class TwoFactorEnabledResult
    {
        /// <summary>
        /// Gets or sets a value indicating whether Two-Factor Authentication is enabled.
        /// </summary>
        public required bool TwoFactorEnabled { get; init; } = false;
    }
}
